#!/usr/bin/python
#coding:utf-8
import os, sys
import subprocess
import re

def commit(_msg):
	
	if len(_msg) > 0:

		pattern = re.compile('\[B\d{6}-.{3}\]')
		isMatch = pattern.match(_msg)
		if isMatch:
			push()
		else:
			line = ''
			commitMsg = "%s %s" % ("git commit -m", '\"PD2000:[B151026-xxx] ' + _msg + '\"')
			pattern = re.compile('\[.+?\]')
			p = subprocess.Popen(commitMsg, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
			isCommitOk = False
			for line in p.stdout.readlines():
				print(line)
				isCommitOk = pattern.match(line)
				if (isCommitOk):
					break

			if isCommitOk:
				print('commit success and start to push changes to server please wait...')
				push()
			else:
				print('something is error')

def push():
	
	line=''
	push=''
	pattern = re.compile('[*]')
	p = subprocess.Popen('git branch', shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
	for line in p.stdout.readlines():
		match = pattern.match(line)
		if (match):
			push = 'git push origin HEAD:refs/for/' + line[2:]
			break
	print('your branch head is '+line)
	print('start to push changes to server please wait...')
	os.system(push)

def main():
    
    argsLen = len(sys.argv)
    if argsLen > 1:
    	commit(sys.argv[1])
    else:
    	push()

if __name__=="__main__":
    main()